package com.lcredu.web;

import com.google.gson.Gson;
import com.lcredu.bean.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author 黎长容
 * @date 2025-07-18 18:15
 */
@Controller
@RequestMapping("/user")
public class UserHandler {

    /**
     * 1. method=RequestMethod.POST: 表示请求 buy 目标方法必须是 post
     * 2. RequestMethod 四个选项 POST, GET, PUT, DELETE
     * 3. SpringMVC 控制器默认支持 GET 和 POST 两种方式
     * SpringMVC 控制器默认支持GET和POST两种方式, 也就是你不指定 method , 可以接收
     * GET 和 POST 请求
     *
     * @return
     */
    @RequestMapping(value = "/buy", method = RequestMethod.POST)
    public String buy() {
        System.out.println("购买商品");
        return "success";
    }


    //查询书籍,必须要带参数id
    //如果我限制id必须等于200呢?
    @RequestMapping(value = "/search", params = "bookId=200")
    public String search(String bookId) {
        System.out.println("获取到书籍ID=" + bookId);
        return "success";
    }

    //要求可以配置 /user/message/aa, /user/message/aa/bb/cc
    @RequestMapping("/message/**")
    public String message() {
        System.out.println("发送消息");
        return "success";
    }


    //路径变量:接受用户名和id
    @RequestMapping(value = "/reg/{username}/{userId}")
    public String register(@PathVariable("username") String name, @PathVariable("userId") String id) {
        System.out.println("接收到名为:" + name + " 的id为" + id);
        return "success";
    }

    //url不能重复
    @RequestMapping("/hi")
    public String sayHi() {
        System.out.println("hi");
        return "success";
    }

//    @RequestMapping("/hi")
//    public void sayHi2(){
//        System.out.println("hi");
//    }


    //要求:接受一个JSON格式,包装成一个人
    @PostMapping("/savePerson")
    public void savePerson(String name, Integer age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        Gson gson = new Gson();
        String json = gson.toJson(person);
        System.out.println(json);

    }

}
